package edu.chl.food_store.beans.control;

import edu.chl.food_store.beans.ejb.CustomerEJB;
import edu.chl.food_store.beans.model.LoginModelBean;
import edu.chl.food_store.entities.Customer;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.*;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

/**
 * LoginControllerBean:
 * Handles login/logout.
 */
@ManagedBean
@RequestScoped
public class LoginControllerBean implements Serializable {

    @EJB
    private CustomerEJB customerEjb;
    @ManagedProperty(value = "#{loginModelBean}")
    private LoginModelBean loginStatus;

    public void login() {
        FacesMessage msg = null;
        //Log in and set message accordingly
        Customer customer = customerEjb.validateCustomer(loginStatus.getEmail(), loginStatus.getPassword());
        if (customer != null) {
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", loginStatus.getEmail());
            loginStatus.setLoggedIn(true);
            loginStatus.setAdmin(customer.isAdministrator());
        } else {
            msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Username or password is incorrect!", "");
        }
        //Show message
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public void logout() {
        loginStatus.setLoggedIn(false);
        loginStatus.setAdmin(false);
    }

    public LoginModelBean getLoginStatus() {
        return loginStatus;
    }

    public void setLoginStatus(LoginModelBean loginStatus) {
        this.loginStatus = loginStatus;
    }
}
